package com.smxy.mall.controller;

import com.smxy.mall.common.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/common")
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public Object upload(HttpServletRequest request, @RequestParam("files") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }

        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        //String filePath = request.getServletContext().getRealPath(" ")+File.separator+"uploadImg"+File.separator+fileName;
        String filePath = "D:\\code\\java\\mall\\src\\main\\resources\\static\\uploadImg\\";
        File dest = new File(filePath+fileName);

        //dest.getParentFile().mkdirs();
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功");
            Map<String,String> map = new HashMap<>();
            map.put("url","http://localhost:8083/uploadImg/"+fileName);
            //map.put("url","http://192.168.112.159:8083/uploadImg/"+fileName);
            map.put("fileName",fileName);
            return Response.success(map);
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return Response.fail("上传失败");
    }
}
